package com.qiall;

import com.qiall.datautil.RandomUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.nio.charset.StandardCharsets;

import java.util.Map;

public class FreeMarkParserUtil extends ParseService {


    public static String DATA_DIR =  System.getProperty("FREE_MARK_DATA_DIR");

    @Override
    public  String parse(String templateXMl, Map<String, Object> params) {


        Configuration cfg = new Configuration();
        // 设置配置实例信息
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        File file=null;
        try {
            cfg.setDirectoryForTemplateLoading(new File(DATA_DIR));
            cfg.setDefaultEncoding("UTF-8");
            String templateName = RandomUtil.randomNum(5);
             file = new File(DATA_DIR + templateName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(templateXMl.getBytes(StandardCharsets.UTF_8));
            fileOutputStream.close();
            Template template = cfg.getTemplate(templateName);
            StringWriter out = new StringWriter(1000);
            template.process(params, out);
            String outString = out.getBuffer().toString();
            return outString;
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        finally {
            if(file.exists()){
                file.delete();
            }
        }
        return "";

    }

    @Override
   public ParseTypeEnum getType(){
        return ParseTypeEnum.FREE_MARK;
   }
}
